/*
 * When user s	elect configuration menu this class will be called and from this configdetail page will be called using particular id.
 */
package com.fipl.taksar;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.fipl.parse.ParserConfig;

public class ConfigurationActivity extends Activity {
	
	private String regID=null;
	private boolean tkmeFailure = false;
	private boolean sensorFailure = false;
	private boolean variable_outof_Range = false;
	@SuppressWarnings("unused")
	private ProgressDialog progressDialog;
	private Bundle savedInstanceState;
	private int size;
	private String dbName;
	private String client;
	private ArrayList<String> id_ConfigList = new ArrayList<String>();
	private ArrayList<String> equipoList = new ArrayList<String>();
	private ArrayList<String> fechaList = new ArrayList<String>();
	private AlertDialog.Builder builder;
	private String[] notification = {"TKME Failure notification","Sensor Failure notification","Variable out of range"};
	private ListView listView;
	private LinearLayout linearLayout;
	private String[] equipo;
	private AlertDialog alertDialog;
	private String[] fecha;
	private StringBuffer jsontext;		// = new StringBuffer();
	private Context context;

	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		
		this.savedInstanceState=savedInstanceState;
		setContentView(R.layout.configure);
		context = getApplicationContext();
		jsontext = new StringBuffer();
		linearLayout = (LinearLayout)findViewById(R.id.middlescroll);
		
		Log.d("System out", "bool val "+((GlobalData)this.getApplicationContext()).isLoginFlag());
		
		
		//en general , detecta si el usuario ya esta autenticado , o si requiere desplegar 
		//el dialogo login
		if( ((GlobalData)this.getApplicationContext()).isLoginFlag() ){
			setResult(1);	
			getData();
		}		
	}

	public void setData(){
		try{
			JSONArray jsonArray = new JSONArray(jsontext.toString());
			for(int i=0; i<jsonArray.length();i++){
				JSONObject object = jsonArray.getJSONObject(i);
				dbName = object.getString("dbname");
			}
			
			((GlobalData)this.getApplicationContext()).setLoginFlag(true);
			((GlobalData)this.getApplicationContext()).setDbName(dbName);
			Log.d("System out", "bool val "+((GlobalData)this.getApplicationContext()).isLoginFlag());
			
		}catch (Exception e) {
			// TODO: handle exception
			Log.d("System out", "Error "+dbName+e.getMessage());
		}
		SelectNotification();
	}

	public void SelectNotification(){
		
		LayoutInflater layoutInflater = (LayoutInflater)ConfigurationActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
		View view = layoutInflater.inflate(R.layout.notification, (ViewGroup)findViewById(R.id.mainLayoutNoti));
		builder = new AlertDialog.Builder(ConfigurationActivity.this);
		builder.setTitle("Pick Notification");
		builder.setView(view);

		ListView listView = (ListView)view.findViewById(R.id.listViewNoti);
		listView.setAdapter(new MyArrayAdapter2(this, notification));

		Button okButton = (Button)view.findViewById(R.id.okBtnNoti);
		okButton.setOnClickListener(okListener);

		Button dismissButton = (Button)view.findViewById(R.id.dismissBtnNoti);
		dismissButton.setOnClickListener(dismissListener);

		alertDialog = builder.create();
		alertDialog.show();

	}

	public void getData(){

		//Aqui es donde guarda la base de datos a analizar
		dbName = ((GlobalData)this.getApplicationContext()).getDbName(); // get db name from global variable which will be stay upto application lavel
		client = ((GlobalData)this.getApplicationContext()).getClientName();
		listView= new ListView(this);
		listView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
		
		//Parse config tiene la pista ahora
		ParserConfig parser = new ParserConfig(dbName,client); // Nos conectamos a la base de datos personalizada
		if(parser.ParseData()==0){
			id_ConfigList=parser.parseConfig.getId_ConfigArrayList();
			equipoList=parser.parseConfig.getEquipoArrayList();
			fechaList = parser.parseConfig.getFechaArrayList();

			size = equipoList.size();
			equipo = new String[1];
			equipo[0]=equipoList.get(size-1);
			fecha = new String[1];
			fecha[0] = fechaList.get(size-1);

			MyArrayAdapter myArrayAdapter = new MyArrayAdapter(this,equipo,fecha);
			listView.setAdapter(myArrayAdapter);
			listView.setFocusable(true);
			listView.setBackgroundColor(Color.WHITE);
			listView.setCacheColorHint(Color.TRANSPARENT);
			listView.setVerticalScrollBarEnabled(false);
			listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
					// TODO Auto-generated method stub
					setID(arg2);
				}
			});

			linearLayout.addView(listView);

		}else{

			/*
			 * below dialog is called when no data is available and -1 is return from the parseconfigdetail class. 
			 */

			AlertDialog.Builder builder = new AlertDialog.Builder(ConfigurationActivity.this);
			builder.setMessage("No data... Try again later");
			builder.setPositiveButton("Ok", new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					onCreate(savedInstanceState);
				}
			});

			builder.setNegativeButton("Cancel", new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					ConfigurationActivity.this.finish();
				}
			});
			builder.show();
		}

	}

	public class MyArrayAdapter extends ArrayAdapter<String> {

		private final Activity context;
		private final String[] equipo;
		private final String[] fecha;

		public MyArrayAdapter(Activity context, String[] equipo, String[] fecha) {
			super(context, R.layout.textlist, equipo);
			this.context=context;
			this.equipo=equipo;
			this.fecha=fecha;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = context.getLayoutInflater();
			View rowView = inflater.inflate(R.layout.textlist, null, true);
			TextView equipoTextView = (TextView) rowView.findViewById(R.id.equipotxt);
			TextView fechaTextView = (TextView) rowView.findViewById(R.id.fechatxt);
			equipoTextView.setText(equipo[position]);
			fechaTextView.setText(fecha[position]);
			return rowView;
		}

	}

	public void setID(int position){

		Bundle bundle = new Bundle();
		bundle.putString("fecha",fecha[0]);
		bundle.putString("id", id_ConfigList.get(size-1));
		Intent intent = new Intent();
		intent.putExtras(bundle);
		intent.setClass(getApplicationContext(), ConfigDetailActivity.class);
		startActivity(intent);

	}

	@Override
	public boolean onKeyDown(int keyCode , KeyEvent keyEvent){

		if(keyCode == KeyEvent.KEYCODE_BACK){
			onDestroy();
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, keyEvent);

	}

	@Override
	public void onDestroy(){
		super.onDestroy();
		ConfigurationActivity.this.finish();
	}

	@Override
	public void onBackPressed(){
		super.onBackPressed();
		finish();
		return;
	}

	@Override
	public void onStop(){
		super.onStop();
		ConfigurationActivity.this.finish();
	}

	@Override
	public boolean onCreateOptionsMenu (Menu menu){
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.option, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem menuItem){

		switch (menuItem.getItemId()) {

		case R.id.menuDb:
			((GlobalData)this.getApplicationContext()).setLoginFlag(false);
			((GlobalData)this.getApplicationContext()).setMenuNo(100);
			Intent intent = new Intent();
			ConfigurationActivity.this.finish();
			intent.setClass(getApplicationContext(), LoginActivity.class);
			startActivity(intent);
			break;

		case R.id.menuExit:
			ConfigurationActivity.this.finish();
			break;

		}

		return true;

	}

	public class MyArrayAdapter2 extends ArrayAdapter<String> {

		private final Activity context;
		private final String[] notiList;

		public MyArrayAdapter2(Activity context, String[] notiList) {
			super(context, R.layout.notificationlist, notiList);
			this.context=context;
			this.notiList=notiList;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = context.getLayoutInflater();
			View rowView = inflater.inflate(R.layout.notificationlist, null, true);
			TextView textView = (TextView)rowView.findViewById(R.id.textNoti);
			
			ToggleButton toggleButton = (ToggleButton)rowView.findViewById(R.id.onoffBtnNoti);
			toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					// TODO Auto-generated method stub

					if(position == 0){
						if(isChecked){
							tkmeFailure = isChecked;
						}
					}else if(position == 1){
						if(isChecked){
							sensorFailure = isChecked;
						}
					}else if(position==2){
						if(isChecked){
							variable_outof_Range = isChecked;
						}
					}
				}
			});
			textView.setText(notiList[position]);
			return rowView;
		}

	}

	android.view.View.OnClickListener okListener = new android.view.View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			PostPush();
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), SelectVariable.class);
			startActivity(intent);
		}
	};

	android.view.View.OnClickListener dismissListener = new android.view.View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			ConfigurationActivity.this.finish();
		}
	};

	public void PostPush(){
		
		alertDialog.dismiss();		
		regID = ((GlobalData)this.getApplicationContext()).getRegistrationID();
		
		if(regID!=null){			
			String tkmeFailureStr;
			String sensorFailureStr;
			String variableFailureStr;
			String url = "http://megan.teksar.com.mx/json.php?dbname=login&action=insert&table=registration&validate=Duplicate,uid,";
			String quotationString = "%22";
			String colonString = ":";
			String commaString = ",";
			String startSqrString = "[";
			String startCurlString = "{";
			String endCurlString = "}";
			String endSqrString = "]";

			if(tkmeFailure){
				tkmeFailureStr = "yes";
			}else{
				tkmeFailureStr = "no";
			}

			if(sensorFailure){
				sensorFailureStr = "yes";
			}else{
				sensorFailureStr = "no";
			}

			if(variable_outof_Range){
				variableFailureStr = "yes";
			}else{
				variableFailureStr = "no";
			}

			String postStr = url+regID+commaString+"tkm_registration&dbname1="+dbName+"&json="
			+startSqrString+startCurlString+quotationString+"uid"+quotationString+colonString+quotationString+regID+quotationString+commaString
			+quotationString+"dbname"+quotationString+colonString+quotationString+dbName+quotationString+commaString
			+quotationString+"tnotification"+quotationString+colonString+quotationString+tkmeFailureStr+quotationString+commaString
			+quotationString+"snotification"+quotationString+colonString+quotationString+sensorFailureStr+quotationString+commaString
			+quotationString+"vrange"+quotationString+colonString+quotationString+variableFailureStr+quotationString
			+endCurlString+endSqrString;

			try{
				String reply = "";
				URL url2 = new URL(postStr);
				HttpURLConnection httpURLConnection = (HttpURLConnection)url2.openConnection();
				InputStream inputStream = httpURLConnection.getInputStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
				StringBuffer buffer = new StringBuffer();
				do{
					reply = br.readLine();
					if(reply != null){
						buffer.append(reply);
					}
				}while(reply !=null);
				if(buffer.toString().trim().equalsIgnoreCase("true")){
					Log.d("System out", "got true reply ");
				}
			}catch (Exception e) {
				// TODO: handle exception
				Log.d("System out", "Error "+e.getMessage());
			}
			
		}else{
			Toast.makeText(getApplicationContext(),"Please try again later for registration", Toast.LENGTH_SHORT).show();
		}
		
	}

	public void GetError(String error){
		alertDialog.dismiss();
		AlertDialog.Builder builder = new AlertDialog.Builder(ConfigurationActivity.this);
		builder.setMessage(error);
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				ConfigurationActivity.this.finish();
			}
		});
		builder.show();
	}
	
	public void callDialog(){
		
		this.progressDialog = ProgressDialog.show(ConfigurationActivity.this,"Please wait", "Connecting.. Please wait..", true);
				
//		final C2DMReceiver c2dmReceiver = new C2DMReceiver();
		
		new Thread(new Runnable(){
			public void run(){
				try{
					do{
					}while(((GlobalData)context.getApplicationContext()).getRegistrationID()!=null);
				}catch (Exception e){
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}
		
	
}